#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<dirent.h>

static void _show_path(const char * path, int depth);
void show_path(const char* path);
static void error_exit(const char * info);

int main(int argc, char ** argv)
{
    if(argc != 2) printf("Usage: %s filepath\n", __FILE__), exit(-1);
    show_path(argv[1]);
    return 0;
}

void show_path(const char* path)
{
    _show_path(path, 0);
}

static void _show_path(const char *path, int depth)
{
    char nextpath[256];
    memset(nextpath, 0, sizeof(nextpath));
    DIR * dir;
    struct dirent* subfile;
    if( (dir = opendir(path)) == NULL) error_exit("open dir error");
    struct stat fileInfo;

    while( subfile = readdir(dir)){
        if( strcmp(subfile->d_name, ".") == 0 || strcmp(subfile->d_name, "..") == 0) ;
        else{
            // 先序遍历， 先将此时的文件名打印出来
            for(int i = 0; i < depth; i++) printf("----");
            printf("%s\n", subfile->d_name);
            // 如果是文件夹，则继续遍历
            if(subfile->d_type == DT_DIR) {
                strcpy(nextpath, path);
                strcat(nextpath, "/");
                _show_path( strcat(nextpath, subfile->d_name), depth + 1); 
            }
        }
    }   
}

static 
void error_exit(const char * info)
{
    perror(info);
    exit(-1);
}